package com.sk.sourcecircle.activity.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.google.zxing.WriterException;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.activity.AddFriendActivity;
import com.sk.sourcecircle.activity.home.activity.ChatActivity;
import com.sk.sourcecircle.activity.home.activity.RoundGroupActivity;
import com.sk.sourcecircle.activity.home.activity.SearchToAddActivity;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.activity.mine.act.FeedBackActivity;
import com.sk.sourcecircle.activity.mine.act.MyAlbumActivity;
import com.sk.sourcecircle.activity.mine.act.MyBusinessActivity;
import com.sk.sourcecircle.activity.mine.act.MyCareActivity;
import com.sk.sourcecircle.activity.mine.act.MyCollectionActivity;
import com.sk.sourcecircle.activity.mine.act.MyFriendActivity;
import com.sk.sourcecircle.activity.mine.act.MyJoinedActivity;
import com.sk.sourcecircle.activity.mine.act.MyOrderActivity;
import com.sk.sourcecircle.activity.mine.act.MySettingsActivity;
import com.sk.sourcecircle.activity.mine.act.NewPepActivity;
import com.sk.sourcecircle.activity.mine.act.PersonlCodeActivity;
import com.sk.sourcecircle.activity.mine.act.SystemSettingsActivity;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.dialog.CustomPhoneDialogFragment;
import com.sk.sourcecircle.dialog.ShareDialogFragment;
import com.sk.sourcecircle.entity.HomePageInfo;
import com.sk.sourcecircle.entity.XiaoMiEntity;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SPUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.LineMenuView;
import com.sk.sourcecircle.view.StarBar;
import com.sk.sourcecircle.zxing.activity.CaptureActivity;
import com.sk.sourcecircle.zxing.encoding.EncodingHandler;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/19.
 */

@RuntimePermissions
public class MineFragment extends BaseFragment implements HandleDataCallBack, View.OnClickListener, IUiListener {
    @BindView(R.id.settings)
    ImageView settings;
    @BindView(R.id.menu)
    ImageView menu;
    @BindView(R.id.search)
    ImageView search;
    @BindView(R.id.my_head)
    ImageView myHead;
    @BindView(R.id.my_name)
    TextView myName;
    @BindView(R.id.vip_level)
    TextView vipLevel;
    @BindView(R.id.des_star)
    StarBar desStar;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.qr_code)
    ImageView qrCode;
    @BindView(R.id.friend_num)
    TextView friendNum;
    @BindView(R.id.care_num)
    TextView careNum;
    @BindView(R.id.album_num)
    TextView albumNum;
    @BindView(R.id.my_release)
    LineMenuView myRelease;
    @BindView(R.id.my_collect)
    LineMenuView myCollect;
    @BindView(R.id.my_new)
    LineMenuView myNew;
    @BindView(R.id.my_order)
    LineMenuView myOrder;
    @BindView(R.id.my_bussiness)
    LineMenuView myBussiness;
    @BindView(R.id.my_xiaomi)
    LineMenuView myXiaomi;
    @BindView(R.id.my_feed_back)
    LineMenuView myFeedBack;
    @BindView(R.id.lm_icon)
    ImageView lmIcon;
    @BindView(R.id.lm_title)
    TextView lmTitle;
    @BindView(R.id.work_phone)
    TextView workPhone;
    @BindView(R.id.tv_num)
    TextView tvNum;
    Unbinder unbinder;

    private HomePageInfo.DataBean.UserInfoBean myInfo;
    private boolean isopen = false;
    PopupWindow popupWindow;
    private int count = 0;


    private LoadingDialog loadingDialog;

    @Override

    protected int getContentView() {
        return R.layout.fragment_mine;
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        Bitmap mBitmap = null;
        try {
            mBitmap = EncodingHandler.createQRCode("type=1&id=" + String.valueOf(MyUtils.getCode(mContext)), 300);
            if (mBitmap != null) {
                Drawable drawable = new BitmapDrawable(mBitmap);
                qrCode.setBackground(drawable);
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(MyUtils.getToken(mContext)!=null&&MyUtils.getToken(mContext).length()>0){
            doRefresh();
        }
    }

    @OnClick({R.id.settings, R.id.menu, R.id.search, R.id.my_head, R.id.my_release, R.id.my_collect, R.id.my_new, R.id.my_order, R.id.my_bussiness, R.id.my_xiaomi, R.id.my_feed_back, R.id.friend_ll, R.id.care_ll, R.id.album_ll, R.id.qr_code, R.id.contact})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.settings:
                intent.setClass(mContext, SystemSettingsActivity.class);
                intent.putExtra("data", myInfo);
                startActivityForResult(intent, 10);
                break;
            case R.id.menu:
                if (!isopen) {
                    showPopWindow();
                } else {
                    isopen = false;
                    popupWindow.dismiss();
                }
                break;
            case R.id.search:
                Intent search = new Intent(mContext, SearchToAddActivity.class);
                startActivity(search);
                break;
            case R.id.my_head:
                intent.setClass(mContext, MySettingsActivity.class);
                intent.putExtra("data", myInfo);
                startActivityForResult(intent, 1);
                break;
            case R.id.my_release:
                intent.setClass(mContext, MyJoinedActivity.class);
                startActivity(intent);
                break;
            case R.id.my_collect:
                intent.setClass(mContext, MyCollectionActivity.class);
                startActivity(intent);
                break;
            case R.id.my_new:
                intent.setClass(mContext, NewPepActivity.class);
                startActivity(intent);
                break;
            case R.id.my_order:
                intent.setClass(mContext, MyOrderActivity.class);
                startActivity(intent);
                break;
            case R.id.my_bussiness:
                intent.setClass(mContext, MyBusinessActivity.class);
                startActivity(intent);
                break;
            case R.id.my_xiaomi:
                loadingDialog.show();
                AppApi.myXiaomi(MineFragment.this, 10, getActivity());
//                intent.setClass(mContext, SystemSettingsActivity.class);
//                startActivity(intent);
                break;
            case R.id.my_feed_back:
                intent.setClass(mContext, FeedBackActivity.class);
                startActivity(intent);
                break;
            case R.id.friend_ll:
                intent.setClass(mContext, MyFriendActivity.class);
                intent.putExtra("count", count);
                startActivity(intent);
                break;
            case R.id.care_ll:
                intent.setClass(mContext, MyCareActivity.class);
                startActivity(intent);
                break;
            case R.id.album_ll:
                intent.setClass(mContext, MyAlbumActivity.class);
                startActivity(intent);
                break;
            case R.id.qr_code:
                Intent codeIntent = new Intent(mContext, PersonlCodeActivity.class);
                codeIntent.putExtra("type", 1);
                codeIntent.putExtra("string", "type=1&id=" + MyUtils.getCode(mContext));
                codeIntent.putExtra("name", MyUtils.getMyInfo(mContext).getNickname());
                codeIntent.putExtra("url", MyUtils.getMyInfo(mContext).getHead_url());
                startActivity(codeIntent);
                break;
            case R.id.contact:
                MineFragmentPermissionsDispatcher.startCallWithPermissionCheck(this);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        switch (tag) {
            case 0:
                HomePageInfo homePageInfo = JSON.parseObject(result, HomePageInfo.class);
                HomePageInfo.DataBean dataBean = homePageInfo.getData();
                myInfo = homePageInfo.getData().getUser_info();
                Glide.with(mContext).load(dataBean.getUser_info().getHead_url()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(myHead);
                myName.setText(dataBean.getUser_info().getNickname());
                desStar.setStarMark(dataBean.getUser_info().getSincerity());
                if (dataBean.getUser_info().getIntroduce() != null) {
                    tvDescribe.setText(dataBean.getUser_info().getIntroduce());
                }
                friendNum.setText(String.valueOf(dataBean.getFriend_count()));
                careNum.setText(String.valueOf(dataBean.getFollow_count()));
                albumNum.setText(String.valueOf(dataBean.getAlbum_count()));
                SPUtils.put(mContext, "pageInfo", result);
                break;
            case 10:
                loadingDialog.cancelDialog();
                XiaoMiEntity entity = JSON.parseObject(result, XiaoMiEntity.class);
                if (entity.getData().get(0).getFriend().getHx_login() != null && entity.getData().get(0).getFriend().getHx_login().length() > 0) {
                    Intent intent = new Intent(mContext, ChatActivity.class);
                    XiaoMiEntity.DataBean.FriendBean friendBean = entity.getData().get(0).getFriend();
                    intent.putExtra("id", friendBean.getHx_login());
                    intent.putExtra("toName", friendBean.getNickname());
                    intent.putExtra("toUrl", friendBean.getHead_url());
                    intent.putExtra("toId", friendBean.getUser_id());
                    startActivity(intent);
                } else {
                    SnackUtils.show(mRootView, "客服尚未准备就绪！");
                }
                break;
            case 1:
                JSONObject jsonObject = JSON.parseObject(result);
                count = jsonObject.getIntValue("data");
                if (count > 0) {
                    tvNum.setVisibility(View.VISIBLE);
                    tvNum.setText(String.valueOf(count));
                } else {
                    tvNum.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    public void doRefresh() {
        AppApi.homePageInfo(MyUtils.getCode(mContext), this, 0, getActivity());
        AppApi.unReadCount(this, 1, getActivity());
    }

    private void showPopWindow() {
        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.home_pop, relativeLayout, false);
        TextView addFriend = view.findViewById(R.id.add_friend);
        TextView roundGroup = view.findViewById(R.id.round_group);
        TextView share = view.findViewById(R.id.share);
        TextView scan = view.findViewById(R.id.scan);
        addFriend.setOnClickListener(this);
        roundGroup.setOnClickListener(this);
        share.setOnClickListener(this);
        scan.setOnClickListener(this);
        relativeLayout.addView(view);
        popupWindow = new PopupWindow(relativeLayout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setClippingEnabled(false);

        ColorDrawable dw = new ColorDrawable(0);
        popupWindow.setBackgroundDrawable(dw);

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        relativeLayout.measure(w, h);
        int width = relativeLayout.getMeasuredWidth();
        popupWindow.showAsDropDown(menu, -width + menu.getMeasuredWidth(), 0);
        isopen = true;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_friend:
                Intent addIntent = new Intent(mContext, AddFriendActivity.class);
                startActivity(addIntent);
                popupWindow.dismiss();
                isopen = false;
                break;
            case R.id.round_group:
                Intent groupIntent = new Intent(mContext, RoundGroupActivity.class);
                startActivity(groupIntent);
                popupWindow.dismiss();
                isopen = false;

                break;
            case R.id.share:
                ShareDialogFragment shareDialogFragment = new ShareDialogFragment();
                shareDialogFragment.setTargetUrl(Constants.App_url);
                shareDialogFragment.setImageUrl("");
                shareDialogFragment.setQqListener(this);
                shareDialogFragment.setTitle("源圈");
                shareDialogFragment.setSummary("源圈社区”是北京源圈传媒科技有限公司自主开发运营的一款APP应用，是消费升级领域首家本地化精准数据匹配平台。以本地化社群APP为载体，用户运营为中心，串连社区、中小微企业、校园三大场景，运用“去中心化”的平台方式，让各实体社群实现精准用户运营、精准需求匹配、精准营销推广。立志成为一个让人人都能实现价值的平台、一个基于实体场景的精准大数据平台。");
                shareDialogFragment.show(getActivity().getFragmentManager(), "share");
                popupWindow.dismiss();
                isopen = false;
                break;
            case R.id.scan:
                popupWindow.dismiss();
                isopen = false;
                MineFragmentPermissionsDispatcher.startScanWithPermissionCheck(this);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case 1:
                    doRefresh();
                    break;
                case 10:
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                    getActivity().finish();
                    break;
            }
        }
    }

    @Override
    public void sure() {
        super.sure();
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + workPhone.getText().toString().replace("-", ""));
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startScan() {
        Intent scanIntent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(scanIntent, 1);

    }

    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void startCall() {
        CustomPhoneDialogFragment customPhoneDialogFragment = new CustomPhoneDialogFragment();
        customPhoneDialogFragment.setContent(workPhone.getText().toString());
        customPhoneDialogFragment.setMyCallBack(MineFragment.this);
        customPhoneDialogFragment.show(getFragmentManager(), "phone");
    }


    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("扫一扫需要使用您的相机！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showRationaleForPhone(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的电话！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        SnackUtils.showError(mRootView, "您拒绝了相机权限！");
    }


    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showDeniedForPhone() {
        SnackUtils.showError(mRootView, "您拒绝了电话权限！");
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止定位权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showNeverAskForPhone() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止定位权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MineFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
